import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();
// 在页面中定义激励视频广告
let videoAd = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户收藏数据
    userCollectStrategies: [],
    // 所有的数据
    strategyWithCategoryResps: [],

    // 被点击的左侧的菜单
    currentIndex: 0,

    mainActiveIndex: 0,
    activeId: [],
    max: 100,
    items: []
  },
  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },

  onClickItem({
    detail = {}
  }) {
    // 判断是否需要登录
    if (!app.globalData.hasLogin) {
      this.newLoginApi()
    } else {
      const {
        activeId
      } = this.data;
      let collectStrategyCache = wx.getStorageSync('collectStrategy')
      const index = activeId.indexOf(detail.id);
      if (index > -1) {
        util.request(api.StrategyCancelCollect, {
          "strategyId": detail.id,
          "strategyName": detail.text
        }).then(resp => {
          // 取消收藏
          activeId.splice(index, 1);
          let items = this.data.items
          collectStrategyCache.splice(collectStrategyCache.findIndex(item => item.id == detail.id), 1)
          wx.setStorageSync('collectStrategy', collectStrategyCache)
          this.getTabBar().setCartNumber(collectStrategyCache.length)
          // 减去徽标
          for (let idx in items) {
            let item = items[idx]
            let childStrategyIds = item.children.map(strategy => strategy.id)
            if (childStrategyIds.includes(detail.id)) {
              let c = item.badge == undefined ? 0 : item.badge
              item.badge = c - 1
              if (c - 1 == 0) {
                let {
                  badge,
                  ...d
                } = item
                items[idx] = d
              }
            }
          }

          this.setData({
            activeId,
            items
          });
        })
      } else {
        // 如果没有就是新增收藏 判断下是否超过收藏次数, 
        util.request(api.UserInfo).then(resp=>{
            if(resp.success){
                let timeLimit = resp.data.strategyNumber
                let activeIdLength = this.data.activeId.length 
                let incrStrategyNumber = resp.data.incrStrategyNumber
                if(timeLimit > activeIdLength){
                    // 正常收藏策略
                    util.request(api.StrategyCollect, {
                        "strategyId": detail.id,
                        "strategyName": detail.text
                      }).then(resp => {
              
                        if (resp.success) {
                          // 新增收藏
                          activeId.push(detail.id);
                          let items = this.data.items
                          collectStrategyCache.push(detail)
                          wx.setStorageSync('collectStrategy', collectStrategyCache)
                          this.getTabBar().setCartNumber(collectStrategyCache.length)
              
                          // 增加徽标
                          for (let idx in items) {
                            let item = items[idx]
                            let childStrategyIds = item.children.map(strategy => strategy.id)
                            if (childStrategyIds.includes(detail.id)) {
                              let c = item.badge == undefined ? 0 : item.badge
                              item.badge = c + 1
                            }
                          }
                          this.setData({
                            activeId,
                            items: items
                          });
                        } else {
                          wx.showToast({
                            title: resp.message,
                            icon: 'none'
                          })
                        }
                      })
                } else{
                    let msg = '当前已有' + timeLimit + '条策略,\n 获取更多' + incrStrategyNumber +'次选择?'
                    //TODO 弹窗的confirm 颜色设定
                    Dialog.confirm({
                        // title: '标题',
                        message: msg,
                      })
                        .then(() => {
                          // on confirm
                          this.adShow()
                        })
                        .catch(() => {
                          // on cancel
                        });
                }
            }
        })
        
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.adLoad()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    // 后端获取页面
    util.request(api.StrategyIndex).then(resp => {

      this.setData({
        activeId: resp.data.activeId,
        items: resp.data.items
      })
      let data = resp.data.collectStrategyInfo.map(x => {
        return {
          "id": x.id,
          "text": x.text
        }
      })
      wx.setStorageSync('collectStrategy', data)
      this.getTabBar().setCartNumber(data.length)
    })

  },
  adLoad: function () {
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-fa5c215a314f6c37'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {

        
   // 用户点击了【关闭广告】按钮
    if (res && res.isEnded) {
        // 正常播放结束，可以下发游戏奖励
        console.log('成功观看广告, 获取次数');
        util.request(api.IncrStrateyNumber)
      } else {
        // 播放中途退出，不下发游戏奖励
      }
      })
    }
  },
  adShow: function () {
    // 用户触发广告后，显示激励视频广告
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  newLoginApi() {
    if (!app.globalData.hasLogin) {
      wx.getUserProfile({
        desc: '获取你的昵称、头像、地区及性别',
        success: e => {
          console.log('用户信息:', e)
          user.loginByWeixin(e.userInfo).then(res => {
            app.globalData.hasLogin = true;
            // 登录完了. 获取用户收藏的策略. 重新赋值
            // 后端获取页面
            util.request(api.StrategyIndex).then(resp => {
              if (resp.success) {
                this.getTabBar().setCartNumber(resp.data.activeId.length)
                wx.setStorageSync('collectStrategy', resp.data.collectStrategyInfo)
                this.setData({
                  activeId: resp.data.activeId,
                  items: resp.data.items
                })
              }
            })
              // 每日登陆加积分
        util.request(api.DailyFirstLogin).then(resp => {
            if (resp.success && resp.data.firstLogin) {
                wx.showToast({
                    title: '每日登陆.积分 +' + resp.data.rewardPoint,
                    icon: "none"
                })
            }else{
                wx.showToast({
                  title: '登录成功',
                  icon:"success"
                })
            }
        })
          }).catch((err) => {
            app.globalData.hasLogin = false;
            util.showErrorToast('微信登录失败');
          });
        }
      })
    }else{
        wx.showToast({
          title: '请重新登录',
          icon:"none"
        })
    }

  }
})